package mqtt

import (
	"fmt"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"watch_script_state/dto/plugins_handler_dto"
)

var mqttServer plugins_handler_dto.HandlerDTO

var MqttClient MQTT.Client

func Mqtt() plugins_handler_dto.HandlerDTO {
	mqttServer.Name = "MqttServer"
	mqttServer.Description = "mqtt服务"
	mqttServer.Func = run
	return mqttServer
}

var messagePubHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

var connectHandler MQTT.OnConnectHandler = func(client MQTT.Client) {
	// 复制全局变量页面调用使用
	MqttClient = client

	mqttServer.State = 1
	fmt.Println("Mqtt connect Connected")
	// 订阅主题
	client.Subscribe("c/*", 0, func(client MQTT.Client, message MQTT.Message) {
		// 存入redis还是直接赋值页面引用
		fmt.Printf("Received message: %s from topic: %s\n", message.Payload(), message.Topic())
	})
}

var connectLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
	client.Connect()
	println("正在重新连接")
}

func run() {
	// 创建一个 MQTT 选项对象
	opts := MQTT.NewClientOptions()
	opts.AddBroker("tcp://broker.emqx.io:1883")
	opts.SetClientID("go-mqtt-client")
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	// 创建一个 MQTT 客户端
	client := MQTT.NewClient(opts)
	// 连接到 MQTT 代理
	token := client.Connect()
	println("正在连接mqttBroker:", token)

}

func GetMqttServerInfo() plugins_handler_dto.HandlerDTO {
	return mqttServer
}
